package com.sywb.chuangyebao.view;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.pm.ActivityInfo;
import android.content.res.Configuration;
import android.net.ConnectivityManager;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.content.ContextCompat;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.webkit.CookieManager;
import android.webkit.CookieSyncManager;
import android.webkit.JsPromptResult;
import android.webkit.JsResult;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.TextView;

import com.sywb.chuangyebao.Constants;
import com.sywb.chuangyebao.R;
import com.sywb.chuangyebao.contract.BusinessTVDetailContract;
import com.sywb.chuangyebao.library.player.AliPlayerView;
import com.sywb.chuangyebao.library.player.IVideoController;
import com.sywb.chuangyebao.library.player.listener.OnPlayerListener;
import com.sywb.chuangyebao.utils.ScreenSwitchUtils;
import com.sywb.chuangyebao.utils.WindowUtil;
import com.sywb.chuangyebao.widget.RichTextView;

import org.bining.footstone.log.Logger;
import org.bining.footstone.rxjava.rxbus.RxBus;
import org.bining.footstone.rxjava.rxbus.annotation.Subscribe;
import org.bining.footstone.rxjava.rxbus.annotation.Tag;
import org.bining.footstone.rxjava.rxbus.thread.ThreadMode;
import org.bining.footstone.utils.ApkUtils;
import org.bining.footstone.utils.SoftKeyboardUtils;
import org.bining.footstone.widget.ProgressWebView;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * 创TV详情
 */
public class BusinessTVDetailActivity extends ActionbarActivity<BusinessTVDetailContract.Presenter> implements BusinessTVDetailContract.View {

    @BindView(R.id.fl_content)
    FrameLayout flContent;

    @BindView(R.id.sv_content)
    ScrollView svContent;

    @BindView(R.id.ll_container)
    FrameLayout llContainer;

    @BindView(R.id.tv_businesstv_intro)
    TextView tvBusinesstvIntro;
    @BindView(R.id.rtv_businesstv_intro)
    RichTextView rtvBusinesstvIntro;
    @BindView(R.id.wv_content)
    WebView wvContent;

    @BindView(R.id.full_screen)
    FrameLayout fullScreen;

    @BindView(R.id.iv_back)
    ImageView ivBack;
//    @BindView(R.id.iv_operation)
//    ImageView ivOperation;

    @BindView(R.id.tv_businesstv_changtantong)
    TextView tvBusinesstvChangtantong;
    @BindView(R.id.ll_businesstv_changtantong)
    LinearLayout llBusinesstvChangtantong;
    @BindView(R.id.tv_businesstv_msg)
    TextView tvBusinesstvMsg;
    @BindView(R.id.ll_businesstv_msg)
    LinearLayout llBusinesstvMsg;
    @BindView(R.id.tv_businesstv_call)
    TextView tvBusinesstvCall;
    @BindView(R.id.ll_businesstv_call)
    LinearLayout llBusinesstvCall;

    private ScreenSwitchUtils instance;

    private AliPlayerView videoPlayer;

    private boolean isFullScreen = false;//默认为竖屏的情况

    private String tvpId;

    @Override
    public int getLayoutId(Bundle bundle) {
        return R.layout.activity_businesstv_detail;
    }

    @Override
    public void initView(Bundle bundle) {
        super.initView(bundle);
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
        instance = ScreenSwitchUtils.init(this.getApplicationContext());

        if (bundle != null) {
            tvpId = bundle.getString("p0");
        } else {
            tvpId = getIntent().getStringExtra("p0");
        }

        videoPlayer = new AliPlayerView(mContext);
        videoPlayer.setCanShare(false);
        videoPlayer.setOnPlayerListener(new OnPlayerListener() {
            @Override
            public void onInit() {
                ivBack.setVisibility(View.VISIBLE);
//                ivOperation.setVisibility(View.VISIBLE);
            }

            @Override
            public void onPrepared() {
                ivBack.setVisibility(View.GONE);
//                ivOperation.setVisibility(View.GONE);
            }

            @Override
            public void onStarted() {
                ivBack.setVisibility(View.GONE);
//                ivOperation.setVisibility(View.GONE);
                instance.start(mActivity);
            }

            @Override
            public void onPaused() {
                ivBack.setVisibility(View.VISIBLE);
//                ivOperation.setVisibility(View.VISIBLE);
                instance.stop();
            }

            @Override
            public void onCompletion() {
                ivBack.setVisibility(View.VISIBLE);
//                ivOperation.setVisibility(View.VISIBLE);
                instance.stop();
            }

            @Override
            public void onError(int causeCode, int sceneCode, String message) {
                ivBack.setVisibility(View.VISIBLE);
//                ivOperation.setVisibility(View.VISIBLE);
                instance.stop();
            }

            @Override
            public void onShare(int platformType) {
                mPresenter.showDialog();
            }

            @Override
            public void onClickScreenDirection() {
                instance.toggleScreen();
            }

            @Override
            public void showToolsView() {
                ivBack.setVisibility(View.VISIBLE);
//                ivOperation.setVisibility(View.VISIBLE);
            }

            @Override
            public void hideToolsView() {
                ivBack.setVisibility(View.GONE);
//                ivOperation.setVisibility(View.GONE);
            }

            @Override
            public void updateProgress(int curPosition, int bufferPosition, int duration) {
            }

        });

        llContainer.addView(videoPlayer);

        rtvBusinesstvIntro.setExpandView(true);
        rtvBusinesstvIntro.setExpandedOpen(false);
        rtvBusinesstvIntro.setExpandText("展开>");
        rtvBusinesstvIntro.setLinkHighlightColor(ContextCompat.getColor(mContext, R.color.colorTheme));
        rtvBusinesstvIntro.setOnLinkClickListener(new RichTextView.OnLinkClickListener() {
            @Override
            public void onAtClick(RichTextView richTextView, Object userId) {
            }

            @Override
            public void onTopicClick(RichTextView richTextView, Object topicId) {
            }

            @Override
            public void onEmojiClick(RichTextView richTextView, Object emoji) {
            }

            @Override
            public void onUrlClick(RichTextView richTextView, Object url) {
            }

            @Override
            public void onAllClick(RichTextView richTextView) {
                mPresenter.goToIntro();
            }
        });

        synCookies(mContext, Constants.COOKIE_CTV);
        initWebView();
    }

    @Override
    public void initPresenter() {
        mPresenter.initPresenter(this);
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        outState.putString("p0", tvpId);
        super.onSaveInstanceState(outState);
    }

    /**
     * 同步一下cookie
     * context：上下文
     * url要访问的url
     */
    public void synCookies(Context context, String cookie) {
        try {
            // String url = HttpUtils.getHttpUrl() + Constants.POST_GET_CODE + "?version=" + ApkUtils.getVersionName();
            String url = "http://www.3158.cn";

            CookieSyncManager.createInstance(context);
            CookieManager cookieManager = CookieManager.getInstance();

            String cook = cookieManager.getCookie(url);
            System.out.println("getCookie:  -----------" + cook);

            // CookieManager.setAcceptFileSchemeCookies(true);
            // cookieManager.acceptCookie();
            // if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            // cookieManager.acceptThirdPartyCookies(webContent);
            // }

            cookieManager.setAcceptCookie(true);
            cookieManager.removeSessionCookie();// 移除
            // cookieManager.removeAllCookie();

            cookieManager.setCookie(url, "_J_SITE=" + cookie + "-android");

            CookieSyncManager.getInstance().sync();

            cook = cookieManager.getCookie(url);
            System.out.println("getCookie:  -----------" + cook);
        } catch (Exception e) {
        }
    }

    /**
     * 初始化WebView
     */
    @SuppressLint("SetJavaScriptEnabled")
    private void initWebView() {
        /**
         * setAllowFileAccess 启用或禁止WebView访问文件数据 setBlockNetworkImage 是否显示网络图像
         * setBuiltInZoomControls 设置是否支持缩放 setCacheMode 设置缓冲的模式
         * setDefaultFontSize 设置默认的字体大小 setDefaultTextEncodingName 设置在解码时使用的默认编码
         * setFixedFontFamily 设置固定使用的字体 setJavaSciptEnabled 设置是否支持Javascript
         * setLayoutAlgorithm 设置布局方式 setLightTouchEnabled 设置用鼠标激活被选项
         * setSupportZoom 设置是否支持变焦
         * */
        WebSettings settings = wvContent.getSettings();
        settings.setJavaScriptEnabled(true);// 设置支持javascript脚本
        settings.setJavaScriptCanOpenWindowsAutomatically(true);
        settings.setCacheMode(WebSettings.LOAD_NO_CACHE);
        // 1.NARROW_COLUMNS：可能的话使所有列的宽度不超过屏幕宽度；2.NORMAL：正常显示不做任何渲染；3.SINGLE_COLUMN：把所有内容放大webview等宽的一列中
        // settings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.NORMAL);// 排版适应屏幕
        settings.setDisplayZoomControls(false);
        settings.setAllowFileAccess(true); // 启用或禁止WebView访问文件数据
        settings.setBuiltInZoomControls(false); //  隐藏缩放按钮
        settings.setSupportZoom(true); // 支持缩放
        // settings.setUseWideViewPort(true);// 可任意比例缩放
        settings.setLoadWithOverviewMode(true);//setUseWideViewPort方法设置webview推荐使用的窗口；设置webview加载的页面的模式
        settings.setGeolocationEnabled(true);// 启用地理定位
        settings.setDomStorageEnabled(true);
        settings.setSaveFormData(true);// 保存表单数据
        // settings.setSavePassword(true);
        // settings.setTextZoom(200);
        // settings.setMixedContentMode(1);
        // settings.setAcceptThirdPartyCookies();
        wvContent.setWebViewClient(new WebViewClient() {
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                view.loadUrl(url);
                return false;
            }
        });

        wvContent.setWebChromeClient(new WebChromeClient() {

            @Override
            public boolean onJsAlert(WebView view, String url, String message, final JsResult result) {

                AlertDialog.Builder b2 = new AlertDialog.Builder(mContext).setMessage(message).setPositiveButton("确定",
                        new AlertDialog.OnClickListener() {

                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                // TODO Auto-generated method stub
                                result.confirm();
                            }
                        });
                b2.setCancelable(false);
                b2.create();
                b2.show();

//                AlertDialog alertDialog = AlertDialog.newInstance(null, message, "确定", null, true);
//                alertDialog.setClickListener(new AlertDialog.OnClickListener() {
//                    @Override
//                    public void onClick(int position) {
//                        result.confirm();
//                    }
//                });
//                alertDialog.show(getFragmentManager(), "BusinessTV");

                return true;
            }

            @Override
            public boolean onJsConfirm(WebView view, String url, String message, JsResult result) {
                // TODO Auto-generated method stub
                return super.onJsConfirm(view, url, message, result);
            }

            @Override
            public boolean onJsPrompt(WebView view, String url, String message, String defaultValue, JsPromptResult result) {
                // TODO Auto-generated method stub
                return super.onJsPrompt(view, url, message, defaultValue, result);
            }
        });
    }

    @OnClick({R.id.iv_operation, R.id.ll_businesstv_changtantong, R.id.ll_businesstv_msg, R.id.ll_businesstv_call, R.id.tv_businesstv_intro})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.iv_operation:
                mPresenter.showDialog();
                break;
            case R.id.ll_businesstv_changtantong:
                mPresenter.goToChangtantong();
                break;
            case R.id.ll_businesstv_msg:
                Logger.e(" svContent.getHeight():" + svContent.getMeasuredHeight() + " wvContent.getMeasuredHeight():" + wvContent.getHeight());
                svContent.scrollTo(0, llContainer.getHeight() + tvBusinesstvIntro.getHeight() + rtvBusinesstvIntro.getHeight());
                break;
            case R.id.ll_businesstv_call:
                svContent.fullScroll(ScrollView.FOCUS_DOWN);
                break;
            case R.id.tv_businesstv_intro:
                mPresenter.goToIntro();
                break;
        }
    }

    @Subscribe(thread = ThreadMode.MAIN_THREAD, tags = {@Tag(ConnectivityManager.CONNECTIVITY_ACTION)})
    public void netwotkChange(String data) {
        Logger.e("netwotkChange:" + data);
        videoPlayer.inspectPlayer();
    }

    @Override
    public boolean useRxBus() {
        return true;
    }

    /**
     * 横竖屏切换
     *
     * @param newConfig
     */
    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        boolean orientation = newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE;//屏幕方向是否为横屏
        Logger.e("屏幕方向改变！！！是否为横屏：" + orientation);
        videoPlayer.onConfigurationChanged(newConfig);
        videoPlayer.requestFocus();
        if (orientation) {// 横屏
            if (mActivity == null) return;
            Activity activity = WindowUtil.scanForActivity(mActivity);
            if (activity == null) return;
            if (isFullScreen) return;
            isFullScreen = true;
            WindowUtil.hideSystemBar(mActivity);

            ViewGroup viewGroup = (ViewGroup) videoPlayer.getParent();
            if (viewGroup != null) {
                viewGroup.removeAllViews();
            }

            ViewGroup contentView = activity.findViewById(android.R.id.content);
            FrameLayout.LayoutParams params = new FrameLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
            contentView.addView(videoPlayer, params);
//            new Handler().postDelayed(new Runnable() {
//                @Override
//                public void run() {
//                    svContent.scrollTo(0, 0);
//                    svContent.
//                }
//            }, 1000);
            wvContent.clearFocus();
            SoftKeyboardUtils.stopSoftKeybord(wvContent);
        } else {// 竖屏
            if (mActivity == null) return;
            Activity activity = WindowUtil.scanForActivity(mActivity);
            if (activity == null) return;
            if (!isFullScreen) return;
            isFullScreen = false;
            WindowUtil.showSystemBar(mActivity);
            ViewGroup contentView = activity.findViewById(android.R.id.content);
            contentView.removeView(videoPlayer);

            llContainer.addView(videoPlayer);

        }
    }

    /**
     * 返回键的处理
     */
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            // 横屏播放的情况
            if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE) {
                setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
                return true;
            } else {
                exit();
            }
        }
        return false;
    }

    @OnClick(R.id.iv_back)
    public void onViewClicked() {
        if (isFullScreen) {
            videoPlayer.changedConfiguration();
        } else {
            exit();
        }
    }

    @Override
    protected void onResume() {
        videoPlayer.autoResume();
        super.onResume();
    }

    @Override
    protected void onPause() {
        videoPlayer.autoPause();
        instance.stop();
        super.onPause();
    }

    @Override
    protected void onDestroy() {
        videoPlayer.destroy();
        super.onDestroy();
    }

    @Override
    public int getDialogViewHeight() {
        return content.getHeight() - videoPlayer.getHeight();
    }

    @Override
    public String getBusinessTVId() {
        return tvpId;
    }

    @Override
    public void startPlay(String videoUrl, String previewPath) {
        videoPlayer.init(mActivity, IVideoController.MODE_VIDEO, videoUrl, previewPath, "00:00");
        videoPlayer.start();
    }

    @Override
    public void initData(String intro, String webContent) {
        rtvBusinesstvIntro.setRichText(intro, null);
        wvContent.loadUrl(webContent + "&site=" + Constants.COOKIE_CTV + "-android");
    }

}
